import { hexMD5 } from "./common/md5.js"
import store from './store/index.js';
	
export default {
	config: {
		baseUrl: "http://jvestest.aibafang.com",		// 开发环境 http://app.aibafang.com		http://admin.orange2.com
		servicUrl:"http://jvestest.aibafang.com", 		//	生产环境 测试 http://abf-beta.moqilin.net
		header: {
			'appId':'aibafang',
			'terminal':'main',
			'secret':'303a6f8a23aea4163b6e838098e36450'
		},
		data: {}, 
		method: "GET",
		dataType: "json",  /* 如设为json，会对返回的数据做一次 JSON.parse */
		responseType: "text",
		success() {},
		fail() {},
		complete() {}	
	},
	interceptor: {
		request: null,
		response: null
	},
	getString(len) {
		len = len || 32;　　
		let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';　　
		let maxPos = chars.length;　　
		let pwd = '';
		for(let i = 0; i < len; i++) {
			pwd += chars.charAt(Math.floor(Math.random() * maxPos));　　
		}　　
		return pwd;
	},
	objKeySort(obj) {			// 排序参数对象 
		let newkey = Object.keys(obj).sort();
	　　	let newObj = {};							
		for (let i = 0; i < newkey.length; i++) {	
			newObj[newkey[i]] = obj[newkey[i]];		
		}
		return newObj;			//返回排好序的新对象
	},
	successCode: {
		"200":(res,Success,onSuccess)=>{
			Success(res)
		},
		"250":(res,Success,onSuccess)=>{
			Success(res)
		},
		"490":(res,Success,onSuccess)=>{
			onSuccess(res)
		},
		"500":(res,Success,onSuccess)=>{
			onSuccess(res)
		},
		"429":(res,Success,onSuccess)=>{
			onSuccess(res)
		},
		// "404":(res,Success,onSuccess)=>{
		// 	onSuccess(res)
		// },
		"401":(res,Success,onSuccess)=>{
			//console.log('server token :'+store.state.token)
			store.commit('logout')
			uni.showModal({
			    title: '提示',
			    content: '您未登录系统,请先登录。',
			    success: function (res) {
			        if (res.confirm) {
						// #ifdef H5
						let d = new Date();
						d.setTime(d.getTime() + (-1 * 24*60*60*1000));
						let expires = "expires="+d.toUTCString();
						document.cookie = "access-token='';" + expires;
						// #endif
						uni.navigateTo({
			        		url: '/pages/login/login/login'
			        	}); 
			        }
			    }
			});
		},
		"450":(res,Success,onSuccess)=>{
			//console.log('server token :'+store.state.token)
			store.commit('logout')
			uni.showModal({
			    title: '提示',
			    content: '您未登录系统,请先登录。',
			    success: function (res) {
			        if (res.confirm) {
						// #ifdef H5
						let d = new Date();
						d.setTime(d.getTime() + (-1 * 24*60*60*1000));
						let expires = "expires="+d.toUTCString();
						document.cookie = "access-token='';" + expires;
						// #endif
						uni.navigateTo({
							url: '/pages/login/login/login'
						});
					}
				}
			});
		},
		"451":(res,Success,onSuccess)=>{
			uni.hideLoading()
			// #ifdef APP-PLUS
			uni.showModal({
			    title: '提示',
			    content: '您未注册系统,请先注册。',
			    success: function (res) {
			        if (res.confirm) {
						// #ifdef H5
						let d = new Date();
						d.setTime(d.getTime() + (-1 * 24*60*60*1000));
						let expires = "expires="+d.toUTCString();
						document.cookie = "access-token='';" + expires;
						// #endif
			        	uni.navigateTo({
			        		url: '/pages/login/register/register'
			        	});
			        }
			    }
			});
			// #endif
			// #ifdef H5
			uni.showModal({
			    title: '提示',
			    content: '请联系您的推荐人。',
			    success: function (res) {
			       
			    }
			});
			// #endif
		},
		"480":(res,Success,onSuccess)=>{
			// #ifdef APP-PLUS  
			//let data = JSON.parse(res.data.message)
			openVersion(res.data.data)
			// #endif  
		}
	},
	objForEachMd5(obj) {		// 遍历对象 签名
		let getSign = ''
		Object.keys(obj).forEach(function(key){		
			getSign = hexMD5(hexMD5(obj[key]) + getSign)
		});
		return getSign;			//返回签名好的新对象
	},
	onSuccess(res) {			// 处理请求成功的错误信息
		let msg = res.data.message
		if(res.data.code == 500){
			msg = '系统繁忙'
		}
		uni.showToast({
			title: msg,
			position:'bottom'
		})		
	},
	onFail(err) {				// 处理请求失败的错误信息
		//console.log('错误：' + JSON.stringify(err))
		uni.showToast({
			title: '网络不佳',
			position:'bottom'
		})	
	},
    request(options,Success,Fail,SystemInfo) {
		if (!options) {
			options = {}
		}
		// 生产环境
		if (process.env.NODE_ENV === 'production') {
			options.baseUrl = this.config.servicUrl
		}
		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = options.baseUrl + options.url
		options.data = options.data || {}
		
		
		// header
		//console.log(SystemInfo.version)
		// #ifdef APP-PLUS  
			let _time = {'time': ''+Date.parse(new Date()) / 1000+''},
			_device = {'device': SystemInfo.platform},
			_nonce = {'nonce': this.getString(16)},
			_version = {'version': plus.runtime.version}			
		// #endif 
		
		// #ifdef H5
			let _time = {'time': ''+Date.parse(new Date()) / 1000+''},
			_device = {'device': 'H5'},
			_nonce = {'nonce': this.getString(16)},
			_version = {'version': '1.0'}
		// #endif
		
		options.header = Object.assign({}, this.config.header, _time,_device,_nonce,_version) 
		let _sign = {'sign': this.objForEachMd5(this.objKeySort(options.header))},
		_type = {'Content-Type':'application/json;charset=UTF-8'}
		options.header = Object.assign({}, options.header,_type,_sign) 
		
		// 成功
		options.success = (res)  => {
			//console.log('success:',res)
			if(this.successCode[res.data.code]){
				//console.log(res)
				this.successCode[res.data.code](res,Success,this.onSuccess)
			}else{
				Fail(res)
			}
		}
		// 错误
		options.fail = (err) => {
			this.onFail(err)
		}
		//console.log(JSON.stringify(options.header))
		console.log(JSON.stringify(options))
		uni.request(options);
	},
	uploadFile(options,Success,Fail,SystemInfo) {
		if (!options) {
			options = {}
		}
		// 生产环境
		if (process.env.NODE_ENV === 'production') {
			options.baseUrl = this.config.servicUrl
		}
		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.url = options.baseUrl + options.url
		options.name = options.name || 'file'
		options.filePath = options.filePath || '',
		options.formData = options.formData || {}
		
		// header
		// #ifdef APP-PLUS  
			let _time = {'time': ''+Date.parse(new Date()) / 1000+''},
			_device = {'device': SystemInfo.platform},
			_nonce = {'nonce': this.getString(16)},
			_version = {'version': plus.runtime.version}
		// #endif 
		// #ifdef H5
			let _time = {'time': ''+Date.parse(new Date()) / 1000+''},
			_device = {'device': 'H5'},
			_nonce = {'nonce': this.getString(16)},
			_version = {'version': '1.0'}
		// #endif
		options.header = Object.assign({}, this.config.header, _time,_device,_nonce,_version) 
		let _sign = {'sign': this.objForEachMd5(this.objKeySort(options.header))}
		options.header = Object.assign({}, options.header,_sign) 
		
		// 成功
		options.success = (res)  => {
			if(res.data == '' || res.statusCode == 413){
				uni.showToast({
					icon: 'none',
					title: '上传图片大小超过限制',
					position:'bottom'
				})
				return !1
			}
			// 上传接口返回的数据是字符串
			if(typeof res.data == 'string'){
				res.data = JSON.parse(res.data)
			}
			// 
			if(this.successCode[res.data.code]){
				this.successCode[res.data.code](res,Success)
			}else{
				Fail(res)
			}
		}
		// 错误
		options.fail = (err) => {
			this.onFail(err)
		}
		//console.log(JSON.stringify(options))
		uni.uploadFile(options);
	}
}



// #ifdef APP-PLUS
	function openVersion (data) {
		console.log(JSON.stringify(data))
		if(nvMask){
			return !1
		}
		//以下为计算菜单的nview绘制布局，为固定算法，使用者无关关心
		var screenWidth = plus.screen.resolutionWidth
		var screenHeight = plus.screen.resolutionHeight
		var boxWidth = '270';
		var boxLeft = (screenWidth - boxWidth) / 2	
		var boxHeight = screenHeight * 0.5	// 屏幕高度大的一半
		var boxHeight = screenHeight * 0.5	// 屏幕高度大的一半
		if(boxHeight < 350){
			boxHeight = 350
		}if(boxHeight > 430){
			boxHeight = 400
		}
		var boxTop = screenHeight * 0.5 / 2	// 顶部为四分之一高度
		
		var nvMask = new plus.nativeObj.View("nvMask", { //先创建遮罩层
			top: '0px',
			left: '0px',
			height: '100%',
			width: '100%',
			backgroundColor: 'rgba(0,0,0,0.2)'
		});
		nvMask.addEventListener("click", function() { //处理遮罩层点击
			if(data.update_way=='forced'){			//强制更新
				uni.showToast({
					icon: 'none',
					title: "强制更新版本",
					position:'bottom'
				})
			}else{
				nvMask.hide();
				nvView.hide();	
			}
		})
		var nvView = new plus.nativeObj.View("nvView", { //创建底部图标菜单
			top: boxTop + 'px',
			left: boxLeft + 'px',
			right: '10%',
			height: boxHeight +'px',
			width: boxWidth +'px',
			backgroundColor: 'rgb(0,0,0,0)'
		});
		
		
		
		nvView.draw([
			{
				tag: 'rect',//背景白色
				color: '#ffffff',
				position: {
					width: boxWidth +'px',
					top: '0px',
					height: boxHeight +'px',
				},
				rectStyles: {
					radius:'10px'
				}
			},
			{
				tag: 'img',
				id: 'imgwechatfriend',
				src: '/static/vbg.png',
				position: {
					top: '0px',
					left: '0px',
					width: boxWidth +'px',
					height: 'auto'
				}
			},
			{
				tag: 'rect',	//按钮
				id: 'recrBtn',
				position: {
					width: '170px',
					left: '50px',
					right: '50px',
					top: (boxHeight - 80) +'px',
					height: '40px',
				},
				rectStyles: {
					radius:'100px',
					color: '#ffffff',
					borderColor: '#40b9ef',
					borderWidth: '1px'
				}
			},
			{
				tag: 'font',
				id: 'fontbtn',
				text: '立即更新',
				textStyles: {
					size: '16px',
					align: 'center',
					color: '#e52458'
				},
				position: {
					width: '170px',
					left: '50px',
					right: '50px',
					top: (boxHeight - 80) +'px',
					height: '40px',
				}
			},
			{
				tag: 'font',
				id: 'fontTips',
				position: {
					top: (boxHeight - 40) + 'px',
					left: '0px',
					width: boxWidth +'px',
					height: '40px'
				},
				text: '更新新版本获取更多功能',
				textStyles: {
					size: '14px',
					align: 'center',
					color: '#999999'
				}
			},
			{
				tag: 'richtext',
				id: 'tips',
				text: '<p style="text-align:right;font-size:14px;">'+data.update_content+'</p>',
				richTextStyles: {
					size: '16px',
					align: 'center',
					color: '#36aaff'
				},
				position: {
					width: '170px',
					left: '50px',
					right: '50px',
					top: '200px',
					height: '40px',
				}
			}
		])
		
		
		nvView.addEventListener("click", function() { //处理点击
			plus.runtime.openURL(data.download_url)
		})
		
		// 
		nvMask.show()
		nvView.show()
	}
	
	
	// #endif